package src;

// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import src.ocsf.server.AbstractServer;
import src.ocsf.server.ConnectionToClient;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;re
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;
  
  private File fileToReceive;
  private FileOutputStream fos;
  private boolean fileBeingSent = false;
  private int nb, nbFois;
  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port) 
  {
    super(port);
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
   */
  public void handleMessageFromClient(Object msg, ConnectionToClient client)
  {
    //System.out.println("Message received: " + msg + " from " + client);
    if (!transFile(msg, client))
    	this.sendToAllClients(msg);
  }
   
  //DRIDI *-*-*-*-*-*-*-*-*-*-*-*-*
  public void listcli()
  {
	  Thread[] clientThreadList = getClientConnections();
	  for (int i=0; i<clientThreadList.length; i++)
	    {
	      try
	      {
	        System.out.println(((ConnectionToClient)clientThreadList[i]).getInetAddress() + ((ConnectionToClient)clientThreadList[i]).getName());
	      }
	      catch (Exception ex) {}
	    }
  }
  
	//Chap9 ** DRIDI
	public boolean transFile(Object msg, ConnectionToClient client)
	{
		  String[] message = msg.toString().split("%");

		  if (message[0].equals("/SendF"))/* File exchange between clients */
		  {		  
			  nb = nbFois = Integer.parseInt(message[2]);
			  try
			  {
				  client.sendToClient("/OKSendF%" + message[1]);
				  fileToReceive = new File("C:\\Users\\Adam\\Desktop\\test2.txt");
				  fos = new FileOutputStream(fileToReceive); // Ecriture dans le fichier
				  System.out.println("création du fichier");
				  System.out.println("/OKSendF%" + message[1] + " sent to client " + client.getInetAddress());
				  return true;
			  }catch (Exception e) {
				  System.out.println(e.getMessage());
			}
		  }
		  else if (message[0].equals("/ReceiveF"))
		  {	
			  return true;
		  }
		  else if (message[0].equals("/AcceptF"))
		  {	
			  return true;
		  }
		  else if (message[0].equals("/OkSendF"))
		  {	
			  return true;
		  }
		  else if (message[0].equals("/TakeF"))
		  {	
			  if (nb == nbFois)
				  System.out.println("Reception of " + message[1] + " in progress...");
			  while (nb != 0)
			  {
				  try{
					  //fos.write(Byte.parseByte(message[1]));
					  fos.write(message[1].getBytes());
					  nb--;
				  }catch (IOException e) {
					  System.out.println(e.getMessage());
				}
			  }
			  return true;
		  }
		  return false;
	  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println
      ("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println
      ("Server has stopped listening for connections.");
  }
  
  //DRIDI *-*-*-*-*-*-*-*
  /**
   * This method overrides the one in the superclass.  Called
   * when a client connects.
   */
  protected void clientConnected(ConnectionToClient client)
  {
	  //listcli();
  }
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */
  public static void main(String[] args) 
  {
    int port = 0; //Port to listen on

    try
    {
      port = Integer.parseInt(args[0]); //Get port from command line
    }
    catch(Throwable t)
    {
      port = DEFAULT_PORT; //Set port to 5555
    }
	
    EchoServer sv = new EchoServer(port);
    
    try 
    {
      sv.listen(); //Start listening for connections
    } 
    catch (Exception ex) 
    {
      System.out.println("ERROR - Could not listen for clients!");
      
    }
  }
}
//End of EchoServer class